package com.hxzy.controller;

import com.hxzy.pojo.FastDFSFile;
import com.hxzy.pojo.Result;
import com.hxzy.pojo.StatusCode;
import com.hxzy.testutils.MyFastDFS;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Arrays;

@RestController
@RequestMapping("/file")
@CrossOrigin
public class FileController {

    @PostMapping("/upload")
    public String[] upload(@RequestParam("file") MultipartFile file) {
        FastDFSFile fastDFSFile = new FastDFSFile();
        String filename = file.getOriginalFilename();
        String ext = filename.substring(filename.lastIndexOf("."));
        fastDFSFile.setExt(ext);
        fastDFSFile.setName(filename);
        try {
            byte[] bytes = file.getBytes();
            fastDFSFile.setBytes(bytes);
            String[] message = MyFastDFS.upLoadFile(fastDFSFile);
            System.out.println(Arrays.toString(message));
            return message;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @PostMapping("/downLoad")
    public Result downLoad(String group_name,String remote_filename){
        try {
            MyFastDFS.downLoad(group_name,remote_filename);
            return new Result(true, StatusCode.OK,"下载成功！",null);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }








    /***
     * @param multipartFile
     *  @return
     * @throws IOException */
    /*public String saveFile(MultipartFile multipartFile) throws IOException {
        //获取文件名
        String fileName = multipartFile.getOriginalFilename();
        //2. 获取文件内容
        byte[] content = multipartFile.getBytes();
        //3. 获取文件扩展名
        String ext = "";
        if (fileName != null && !"".equals(fileName)) {
            ext = fileName.substring(fileName.lastIndexOf("."));
        }
        //4. 创建文件实体类对象
        FastDFSFile fastDFSFile = new FastDFSFile(fileName, content, ext);
        //5. 上传
        String[] uploadResults = FastDFSClient.upload(fastDFSFile);
        //6. 拼接上传后的文件的完整路径和名字, uploadResults[0]为组名, uploadResults[1]为文件名称和路径
        String path = FastDFSClient.getTrackerUrl() + uploadResults[0] + "/" + uploadResults[1];
        //7. 返回
        return path;
    }*/


}
